package com.hqyj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.hqyj.pojo.Practice;
import com.hqyj.dao.PracticeMapper;

import com.hqyj.service.IPracticeService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;

import java.util.concurrent.TimeUnit;


@Service
public class PracticeServiceImpl implements IPracticeService {
@Autowired
private PracticeMapper practiceMapper;

@Autowired
private RedisTemplate redisTemplate;

    @Override
    public HashMap<String, Object> select(Practice practice) {
        HashMap<String, Object> map = new HashMap<>();
        // 创建分页对象
        Page<Practice> PracticePage = new Page<>(practice.getPage(),practice.getRow());

        QueryWrapper<Practice> PracticeQueryWrapper = new QueryWrapper<>();
        // 定义当前页 的 key
        String curKey = "practice:list:"+practice.getPage()+ ":" +practice.getRow();
        // 定义总条数 key
        String totalKey = "practice:total";

        // 判断当前页的 数据 是否在 Redis 缓存中
        Object obj = redisTemplate.opsForValue().get(curKey);
        if (obj!=null){
            map.put("info", "success");
            map.put("list", redisTemplate.opsForValue().get(curKey));
            map.put("total", redisTemplate.opsForValue().get(totalKey));
        } else {
            Page<Practice> page = practiceMapper.selectPage(PracticePage,PracticeQueryWrapper);
            map.put("info", "success");
            map.put("list", page.getRecords());
            map.put("total", page.getTotal());

            // 把数据存放到 Redis 中
            redisTemplate.opsForValue().set(curKey,page.getRecords(),5, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(totalKey,page.getTotal(),5,TimeUnit.SECONDS);
        }

        return map;
    }

}
